package com.tc.ssoclient.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: tianchao
 * @Date: 2021/11/9 16:04
 * @Description:
 */
@Controller
@Slf4j
public class HelloController {
    @Value("${sso.server.url}")
    String ssoServerUrl;
    /**
     * 无需登录就可以访问
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }
    @GetMapping("/boss")
    public String users(Model model, HttpSession httpSession,@RequestParam(value = "token",required = false) String token){
        if (!StringUtils.isEmpty(token)){
            Map<String,Object> uriVariables = new HashMap<>();
            uriVariables.put("my_sso_token",token);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?my_sso_token="+token, String.class);
            String body = forEntity.getBody();
            log.info("远程访问根据token获取到的用户信息是 {}", body);
            // 去ssoserver获取用户信息
            httpSession.setAttribute("loginUser", body);
        }

        Object loginUser = httpSession.getAttribute("loginUser");
        if (loginUser == null){
            //没登录
            return "redirect:"+ssoServerUrl + "?redirect_url=http://localhost:8082/boss";
        }
        List<String> users = new ArrayList<>();
        users.add("张三");
        users.add("李四");
        users.add("王五");
        users.add("8082");
        model.addAttribute("users", users);
        return "userlist";
    }
}
